from django import http
from django.core.paginator import Paginator
from django.shortcuts import render

# Create your views here.
from django.utils.timezone import localdate
from django.views import View

from contents.utils import get_categories
from goods.models import GoodsCategory, SKU, GoodsVisitCount
from goods.utils import get_breadcrumb
from response_code import RET


class ListView(View):
    def get(self,request,category_id,page_num):
        ''' 'cat1':{
             'url':,
             name':
            },
             'cat2':{
              'name':
            },
            'cat3':{
            'name':
            }'''
        # 接收sort参数：如果用户不传，就是默认的排序规则
        sort=request.GET.get('sort','default')
        if sort=='default':
            sort_key='-create_time'
        elif sort=='price':
            sort_key='price'
        elif sort=='hot':
            sort_key='-sales'
        #
        # data={
        #     'cat1':{},
        #     'cat2':{},
        #     'cat3':{},
        # }
        # cat3=GoodsCategory.objects.get(id=category_id)
        # data['cat3']['name']=cat3.name
        # data['cat2']['name']=cat3.parent.name
        # data['cat1']['name']=cat3.parent.parent.name
        # data['cat1']['url']=cat3.parent.parent.goodschannel_set.first().url
        data=get_breadcrumb(category_id)
        skus=SKU.objects.filter(category_id=category_id,is_launched=True).order_by(sort_key)
        #每页商品数
        per_page=4
        pages=Paginator(skus,per_page)
        #获取指定页
        page=pages.page(page_num)
        #总页数
        total_page=pages.num_pages
        #当前页
        current_page=page.number
        sku_list=page.object_list
        category_data=get_categories()
        context={
            #获取分类信息
            "categories": category_data,
            "breadcrumb": data,
            'sku_list': sku_list,
            'current_page': current_page,
            'total_page': total_page,
            'category_id': category_id,
            'sort':sort
        }
        return render(request, 'list.html',context=context)

class HotGoodsView(View):
    def get(self,request,category_id):
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id':sku.id,
                "default_image_url": sku.default_image_url.url,
                'name':sku.name,
                'price':sku.price
            })
        return http.JsonResponse({'code': RET.OK, 'errmsg': 'OK', 'hot_skus': hot_skus})
class DetailView(View):
    def get(self,request,sku_id):
        try:
           sku=SKU.objects.get(id=sku_id)
        except Exception as e:
           pass
        category_data = get_categories()
        breadcrumb=get_breadcrumb(sku.category_id)
        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        context = {
            "categories": category_data,
            'breadcrumb': breadcrumb,
            'sku':sku,
            'specs': goods_specs,
        }

        return render(request,'detail.html',context=context)

class DetailVisitView(View):
    def post(self,request,category_id):
        try:
            category=GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return http.HttpResponseForbidden('缺少必传参数')
        today=localdate()
        # print(today)
        try:
            visit_count=GoodsVisitCount.objects.get(date=today,category_id=category_id)
            visit_count.count+=1
            visit_count.save()
        except Exception as e:
            visit_count = GoodsVisitCount.objects.create(
                date=today,
                category_id=category_id,
                count=1
            )
        return http.JsonResponse({'code': RET.OK, 'errmsg': 'OK'})
class GoodsCommentView(View):
    def get(self,request,sku_id):
        user=request.user
        try:
            sku=SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.JsonResponse({'code':RET.PARAMERR,'errmsg':'商品信息有误'})
        '''{
        "code":"0",
        "errmsg":"OK",
        "comment_list":[
        {
            "username":"itcast",
            "comment":"这是一个好手机！",
            "score":4
                }
            ]
        }'''
        comment_list=[]
        order_goods_all=sku.ordergoods_set.all()
        for order_goods in order_goods_all:
            if order_goods.is_anonymous:
                username=user.username[0]+'****'+user.username[-1]
            else:
                username=user.username
            comment_list.append({
                'username':username,
                'comment':order_goods.comment,
                'score':order_goods.score
            })
        return http.JsonResponse({'code':RET.OK,'errmsg':'页面获取成功','goods_comment_list':comment_list})